<template>
  <el-dialog class="xiaobu-form-dialog" v-bind="$attrs" v-on="$listeners">
    <div class="el-dialog-body-child">
      <el-form
        ref="dialogFormRef"
        class="clearfix"
        :model="dialogForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item class="all" prop="oldPassword" label="旧密码">
          <el-input v-model="dialogForm.oldPassword" type="password" placeholder="请输入旧密码" clearable />
        </el-form-item>
        <el-form-item class="all" prop="newPassword" label="新密码">
          <el-input v-model="dialogForm.newPassword" type="password" placeholder="请输入新密码" clearable />
        </el-form-item>
        <el-form-item class="all" prop="confirmPassword" label="确认密码">
          <el-input v-model="dialogForm.confirmPassword" type="password" placeholder="请输入确认密码" clearable />
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <template>
        <el-button @click="$emit('close')">关 闭</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </template>
    </div>
  </el-dialog>
</template>
<script>
import {MD5} from "crypto-js"
import {commonApi} from "@/api"
export default {
  name: "EditUserInfo",
  data() {
    const checkRepeatPwd = (rule, value, callback) => {
      if (value === ""){
        callback(new Error("请输入确认密码"))
      } else if (value !== this.dialogForm.newPassword) {
        callback(new Error("两次输入密码不一致，请重新输入"))
      } else {
        callback()
      }
    }
    return {
      dialogForm: {
        oldPassword: "",
        newPassword: "",
        confirmPassword: ""
      },
      rules: {
        oldPassword: [{required: true, message: "请输入旧密码", trigger: ["blur", "change"]}],
        newPassword: [
          {required: true, message: "请输入新密码", trigger: ["blur", "change"]}
        ],
        confirmPassword: [
          { required: true, message: "请输入确认密码", trigger: ["blur", "change"] },
          {validator: checkRepeatPwd, trigger: ["blur"]}
        ]
      }
    }
  },
  created() {
    this.resetDialogForm()
  },
  methods: {
    // 重置表单
    resetDialogForm() {
      this.dialogForm = {
        oldPassword: "",
        newPassword: "",
        confirmPassword: ""
      }
      this.$nextTick(() => {
        this.$refs.dialogFormRef&&this.$refs.dialogFormRef.clearValidate()
      })
    },
    // 保存个人信息
    save() {
      this.$refs.dialogFormRef.validate(async valid => {
        if (valid) {
          const params = {
            oldPassword: MD5(this.dialogForm.oldPassword).toString(),
            newPassword: MD5(this.dialogForm.newPassword).toString(),
            confirmPassword: MD5(this.dialogForm.confirmPassword).toString()
          }
          commonApi.editPassword(params).then(data => {
            this.$emit("close")
            this.$modal.msgSuccess(data.msg)
          })
        }
      })
    }
  }
}
</script>
